package ldk.xposed.dexreplace.classloaders

import android.util.Log
import dalvik.system.PathClassLoader
import de.robv.android.xposed.XposedBridge
import de.robv.android.xposed.XposedHelpers
import java.lang.reflect.InvocationTargetException

/**
 * Created by liangdengke on 2018/5/9.
 */
class MiddleClassLoader(dexPath: String?, parent: ClassLoader?,
                        private val delegateClassLoader: ClassLoader)
    : PathClassLoader(dexPath, parent) {
    companion object {
        private val TAG = "MiddleClassLoader"
    }

    override fun findClass(name: String?): Class<*> {
        try {
            val result = super.findClass(name)
            XposedBridge.log("MiddleClassLoader: replace: $name")
            return result
        }catch (e: ClassNotFoundException){
            val findMethod = XposedHelpers.findMethodBestMatch(delegateClassLoader::class.java, "findClass", String::class.java)
            try {
                return findMethod.invoke(delegateClassLoader, name) as Class<*>
            }catch (e: InvocationTargetException){
                throw e.targetException
            }
        }
    }
}